﻿using Newtonsoft.Json;
using RXY_Mall.Core;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using RXY_Mall.Services.Goods.Dto;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

namespace RXY_Mall.Services.Goods
{
    public class GoodsService : IGoodsService
    {
        private RXY_MallContext db;

        public GoodsService()
        {
            db = new RXY_MallContext();
        }

        /// <summary>
        /// 批量添加商品分类
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseService<bool>> AddCategories(AddCategoriesInput input)
        {
            ResponseService<bool> result = new ResponseService<bool>();
            result.code = 0;
            try
            {
                var companys = await db.gw_companys.ToListAsync();
                var categories = await db.gw_goods_categories.ToListAsync();
                var cates = input.categories.Where(c => c.api_parent_id == "0").ToList();

                foreach (var item in cates)
                {
                    var company = companys.FirstOrDefault(c => c.api_company_id == item.api_company_id);

                    if (company == null)
                    {
                        result.msg = "公司不存在";
                        return result;
                    }

                    var category = categories.FirstOrDefault(c => c.api_category_id == item.api_category_id);
                    if (category != null)
                    {
                        result.msg = "分类已添加";
                        break;
                    }
                    var parent_id = 0;
                    if (!string.IsNullOrWhiteSpace(item.api_parent_id))
                    {
                        var parent_category = categories.FirstOrDefault(c => c.api_category_id == item.api_parent_id);
                        if (parent_category != null)
                        {
                            parent_id = parent_category.id;
                        }
                    }

                    category = new gw_goods_category()
                    {
                        name = item.category_name,
                        add_time = DateTime.Now,
                        company_id = company.id,
                        parent_id = parent_id,
                        type = 1,
                        icon = "",
                        status = 2,
                        sort = 99,

                        api_category_id = item.api_category_id,
                    };
                    if (parent_id == 0)
                    {
                        category.layer = 1;
                    }
                    else
                    {
                        category.layer = 2;
                    }

                    db.gw_goods_categories.Add(category);
                }

                await db.SaveChangesAsync();

                categories = await db.gw_goods_categories.ToListAsync();
                cates = input.categories.Where(c => c.api_parent_id != "0").ToList();

                foreach (var item in cates)
                {
                    var company = companys.FirstOrDefault(c => c.api_company_id == item.api_company_id);

                    if (company == null)
                    {
                        result.msg = "公司不存在";
                        return result;
                    }

                    var category = categories.FirstOrDefault(c => c.api_category_id == item.api_category_id);
                    if (category != null)
                    {
                        result.msg = "分类已添加";
                        break;
                    }
                    var parent_id = 0;
                    if (!string.IsNullOrWhiteSpace(item.api_parent_id))
                    {
                        var parent_category = categories.FirstOrDefault(c => c.api_category_id == item.api_parent_id);
                        if (parent_category != null)
                        {
                            parent_id = parent_category.id;
                        }
                    }

                    category = new gw_goods_category()
                    {
                        name = item.category_name,
                        add_time = DateTime.Now,
                        company_id = company.id,
                        parent_id = parent_id,
                        type = 1,
                        icon = "",
                        status = 2,
                        sort = 99,

                        api_category_id = item.api_category_id,
                    };
                    if (parent_id == 0)
                    {
                        category.layer = 1;
                    }
                    else
                    {
                        category.layer = 2;
                    }

                    db.gw_goods_categories.Add(category);
                }

                await db.SaveChangesAsync();



                result.code = 1;
                result.msg = "添加成功";
                result.data = true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.code = 2;
                result.msg = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 批量添加品牌
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseService<bool>> AddBrands(AddBrandsInput input)
        {
            ResponseService<bool> result = new ResponseService<bool>();
            result.code = 0;
            try
            {
                var companys = await db.gw_companys.ToListAsync();
                var brands = await db.gw_base_brands.ToListAsync();
                foreach (var item in input.brands)
                {
                    var company = companys.FirstOrDefault(c => c.api_company_id == item.api_company_id);

                    if (company == null)
                    {
                        result.msg = "公司不存在";
                        return result;
                    }

                    var brand = brands.FirstOrDefault(c => c.api_brand_id == item.api_brand_id);
                    if (brand != null)
                    {
                        result.msg = "品牌已添加";
                        break;
                    }

                    brand = new gw_base_brand()
                    {
                        api_brand_id = item.api_brand_id,
                        name = item.brand_name,
                        add_time = DateTime.Now,
                        company_id = company.id,
                        logo = "",
                        sort = 999,
                        status = 0,
                    };

                    db.gw_base_brands.Add(brand);
                }

                await db.SaveChangesAsync();

                result.code = 1;
                result.msg = "添加成功";
                result.data = true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.code = 2;
                result.msg = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 批量添加商品
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseService<bool>> AddGoods(AddGoodsInput input)
        {
            ResponseService<bool> result = new ResponseService<bool>();
            result.code = 0;
            try
            {
                var shops = await db.gw_shops.ToListAsync();
                //var categories = await db.gw_goods_categories.ToListAsync();
                //var brands = await db.gw_base_brands.ToListAsync();
                //var goods_specs = await db.gw_goods_specs.ToListAsync();
                foreach (var item in input.goods)
                {
                    var shop = shops.FirstOrDefault(c => c.api_shop_id == item.api_shop_id);

                    if (shop == null)
                    {
                        result.msg = string.Format("店铺不存在,店铺编号:{0}", item.api_shop_id);
                        return result;
                    }

                    //var category = categories.FirstOrDefault(c => c.api_category_id == item.api_category_id && c.company_id == shop.company_id);
                    //if (category == null)
                    //{
                    //    result.msg = string.Format("分类不存在,分类编号:{0}", item.api_category_id);
                    //    return result;
                    //}

                    //var brand = brands.FirstOrDefault(c => c.api_brand_id == item.api_brand_id && c.company_id == shop.company_id);
                    //if (brand == null)
                    //{
                    //    result.msg = string.Format("品牌不存在,品牌编号:{0}", item.api_brand_id);
                    //    return result;
                    //}

                    var goods = await db.gw_goods.FirstOrDefaultAsync(g => g.api_goods_id == item.api_goods_id);
                    if (goods != null)
                    {
                        break;
                    }

                    goods = new gw_goods()
                    {
                        company_id = shop.company_id,
                        shop_id = shop.id,
                        api_goods_id = item.api_goods_id,

                        //category_id = null,
                        //category_id1 = null,
                        //category_id2 = null,
                        //category_id3 = null,
                        api_category_name = item.api_category_name,
                        api_brand_name = item.api_brand_name,

                        type_id = (byte)GoodsType.Ordinary,
                        type = (byte)GoodsType.Ordinary,
                        name = item.goods_name,
                        spec = item.goods_spec,
                        mnemonic = item.goods_mnemonic,
                        summary = "",
                        description = "",
                        limit_quantity = 999,
                        notify_admin_quantity = 10,
                        remark = "",

                        add_time = DateTime.Now,
                    };

                    var gw_goods_property = new gw_goods_property()
                    {
                        market_price = (decimal)item.skus.FirstOrDefault().sale_price,
                        sale_price = (decimal)item.skus.FirstOrDefault().sale_price,
                        stock_manage_type = 1,
                        published = 0,
                        sort = 999,
                    };
                    goods.gw_goods_property = gw_goods_property;

                    List<gw_goods_sku> lstSkus = new List<gw_goods_sku>();
                    foreach (var _sku in item.skus)
                    {
                        //var spec_name = _sku.specs.FirstOrDefault().spec_key;
                        //var spec_value = _sku.specs.FirstOrDefault().spec_value;
                        //var goods_spec = goods_specs.FirstOrDefault(s => s.name == spec_name);
                        //if (goods_spec == null)
                        //{
                        //    var gw_goods_spec = new gw_goods_spec()
                        //    {
                        //         name= spec_name,                                 
                        //    };
                        //    db.gw_goods_specs.Add(gw_goods_spec);
                        //}

                        //var goods_spec_value = new gw_goods_spec_value()
                        //{
                        //     name= spec_value,
                        //};

                        var sku = new gw_goods_sku()
                        {
                            add_time = DateTime.Now,
                            market_price = _sku.sale_price,
                            sale_price = _sku.sale_price,
                            settlement_price = _sku.sale_price,
                            api_sku_id = _sku.api_sku_id,
                            limit_quantity = 999,
                            notify_admin_quantity = 10,
                            conversion_rate = _sku.conversion_rate,
                            thumb_url = "",
                            api_unit = _sku.api_unit,
                            is_sale = true,
                            published = true,
                        };

                        sku.specs = JsonConvert.SerializeObject(_sku.specs);
                        lstSkus.Add(sku);
                    }
                    goods.gw_goods_sku = lstSkus;

                    db.gw_goods.Add(goods);
                }

                await db.SaveChangesAsync();

                result.code = 1;
                result.msg = "添加成功";
                result.data = true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.code = 2;
                result.msg = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 是否可购买该商品
        /// </summary>
        /// <param name="goods_id"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool IsBuyGoods(int goods_id, out string error)
        {
            bool flag = false;
            error = "";
            var goods = db.gw_goods.Include(g => g.gw_shop)
                .Include(g => g.gw_goods_property)
                .FirstOrDefault(g => g.id == goods_id);

            if (goods == null || goods.deleted == true || goods.gw_goods_property.published != 1)
            {
                error = "商品已下架";
                return flag;
            }

            if (goods.gw_shop.status == 0 || goods.gw_shop.deleted)
            {
                error = "店铺已关闭";
                return flag;
            }

            if (goods.gw_goods_property.is_sale == false)
            {
                error = "无货";
                return flag;
            }

            return true;
        }

        /// <summary>
        /// 是否可以购买SKU商品
        /// </summary>
        /// <param name="sku_id"></param>
        /// <param name="quantity"></param>
        /// <param name="stock_manage_type"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool IsBuySku(int sku_id, int quantity, int stock_manage_type, out string error)
        {
            bool flag = false;
            error = "";
            var sku = db.gw_goods_skus.Find(sku_id);

            if (sku == null || sku.deleted == true)
            {
                error = "商品已下架";
                return flag;
            }

            if (!sku.is_sale)
            {
                error = "暂无货";
                return flag;
            }

            if (sku.limit_quantity != null)
            {
                if (sku.limit_quantity < quantity)
                {
                    error = string.Format("该商品最多可买{0}", sku.limit_quantity);
                    return flag;
                }
            }

            if (stock_manage_type == 2)
            {
                if (sku.stock_quantity == null)
                {
                    error = "暂无货";
                    return flag;
                }

                if (sku.stock_quantity < quantity)
                {
                    error = string.Format("该商品最多可买{0}", sku.stock_quantity);
                    return flag;
                }
            }

            return true;
        }

        /// <summary>
        /// 减少库存
        /// </summary>
        /// <param name="sku_id">Sku编号</param>
        /// <param name="quantity">数量</param>
        /// <param name="error">错误信息</param>
        /// <returns></returns>
        public bool ReduceSku(int sku_id, int quantity, out string error)
        {
            error = "";
            var flag = false;

            using (RXY_MallContext db = new RXY_MallContext())
            {
                //减少库存   
                lock (AppConfig.CurrentAmount)
                {
                    var goods_sku = db.gw_goods_skus.Find(sku_id);
                    if (goods_sku == null && goods_sku.deleted && !goods_sku.is_sale)
                    {
                        error = "该商品已下架";
                        return flag;
                    }

                    if (goods_sku.stock_quantity <= 0)
                    {
                        error = "该商品已售完";
                        return flag;
                    }

                    if (goods_sku.stock_quantity - quantity < 0)
                    {
                        error = "库存仅剩" + goods_sku.stock_quantity;
                        return flag;
                    }
                    LogHelper.WriteLog(string.Format("sku:{0},原库存{1},减少{2}", sku_id, goods_sku.stock_quantity, quantity));
                    goods_sku.stock_quantity -= quantity;
                    db.Entry(goods_sku).Property(p => p.stock_quantity).IsModified = true;

                    if (goods_sku.stock_quantity == 0)
                    {
                        goods_sku.is_sale = false;
                        db.Entry(goods_sku).Property(p => p.is_sale).IsModified = true;
                    }
                    db.SaveChanges();
                    flag = true;
                }
            }

            return flag;
        }

        /// <summary>
        /// 增加库存
        /// </summary>
        /// <param name="sku_id">Sku编号</param>
        /// <param name="quantity">数量</param>
        /// <param name="error">错误信息</param>
        /// <returns></returns>
        public bool AddSku(int sku_id, int quantity, out string error)
        {
            error = "";
            var flag = false;
            try
            {
                using (RXY_MallContext db = new RXY_MallContext())
                {
                    //增加库存   
                    lock (AppConfig.CurrentAmount)
                    {
                        var goods_sku = db.gw_goods_skus.Find(sku_id);
                        if (goods_sku == null)
                        {
                            error = "该商品已下架";
                            return flag;
                        }
                        LogHelper.WriteLog(string.Format("sku:{0},原库存{1},增加{2}", sku_id, goods_sku.stock_quantity, quantity));
                        goods_sku.stock_quantity += quantity;
                        db.Entry(goods_sku).Property(p => p.stock_quantity).IsModified = true;

                        if (!goods_sku.is_sale)
                        {
                            goods_sku.is_sale = true;
                            db.Entry(goods_sku).Property(p => p.is_sale).IsModified = true;
                        }
                        db.SaveChanges();
                        flag = true;
                    }
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
            }

            return flag;
        }
    }
}
